package cn.knet.excel.imp.knetexceltool.thread;

import cn.knet.excel.imp.knetexceltool.DTO.KnetBgdataCompanyBase;
import cn.knet.excel.imp.knetexceltool.service.KnetBgdataCompanyBaseService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.LongAdder;


/*
 * 监听器批处理数据
 * */
public class BasicExcelListener extends AnalysisEventListener<KnetBgdataCompanyBase> {

    private KnetBgdataCompanyBaseService knetBgdataCompanyBaseService;
    private LongAdder global_okAdder = new LongAdder();
    private LongAdder global_failAdder = new LongAdder();
    private LongAdder single_okAdder = new LongAdder();
    private LongAdder single_failAdder = new LongAdder();

    public int smCount = 0;
    private String fileName;

    public BasicExcelListener() {

    }

    public BasicExcelListener(KnetBgdataCompanyBaseService knetBgdataCompanyBaseService, String fileName, LongAdder global_longAdder, LongAdder global_failAdder, LongAdder single_okAdder, LongAdder single_failAdder) {
        this.knetBgdataCompanyBaseService = knetBgdataCompanyBaseService;
        this.fileName = fileName;
        this.global_okAdder = global_longAdder;
        this.global_failAdder = global_failAdder;
        this.single_okAdder = single_okAdder;
        this.single_failAdder = single_failAdder;
    }

    /**
     * 批处理阈值2000
     */
    private static final int BATCH_COUNT = 100;
    List<KnetBgdataCompanyBase> batchList = new ArrayList<KnetBgdataCompanyBase>();

    @Override
    public void invoke(KnetBgdataCompanyBase basic, AnalysisContext analysisContext) {
        //获取对应的行数
        int num = analysisContext.readRowHolder().getRowIndex();
        basic.setRowNum(num + 1);
        batchList.add(basic);
        if (batchList.size() >= BATCH_COUNT) {
            saveData();
            batchList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        // log.info("所有数据解析完成！");

    }

    private void saveData() {
        //调用saveData()方法
        knetBgdataCompanyBaseService.saveCompanyList(batchList, fileName, global_okAdder, global_failAdder,single_okAdder,single_failAdder);
        smCount += batchList.size();
    }
}
